package org.nehc.algorithm.code.leetcode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 字母异位词分组
 * <a href="https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked">leetcode</a>
 *
 * @author 陈賝
 * @since 2024/11/26 09:15
 */
public class group_anagrams_49 {
    public static List<List<String>> groupAnagrams(String[] strs) {
        Collection<List<String>> values = Arrays.stream(strs).collect(Collectors.groupingBy(s -> {
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        })).values();
        return new ArrayList<>(values);
    }

    public static List<List<String>> groupAnagrams2(String[] strs) {
        return new AbstractList<List<String>>() {
            private final List<List<String>> list = new ArrayList<>();
            public void init() {
                if (!list.isEmpty()) {
                    return;
                }
                HashMap<String, List<String>> result = new HashMap<>();
                for (String str : strs) {
                    byte[] strByte = str.getBytes();
                    Arrays.sort(strByte);
                    String sortStr = new String(strByte);
                    List<String> orDefault = result.getOrDefault(sortStr, new ArrayList<>());
                    orDefault.add(str);
                    result.put(sortStr, orDefault);
                }
                list.addAll(result.values());
            }
            @Override
            public List<String> get(int index) {
                return list.get(index);
            }

            @Override
            public int size() {
                init();
                return list.size();
            }
        };
    }

    public static void main(String[] args) {

        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = groupAnagrams(strs);
        List<List<String>> lists2 = groupAnagrams2(strs);
        System.out.println();
    }
}
